# -*- coding: utf-8 -*-
from zc_core.client.mongo_client import Mongo


class DoneFilter(object):
    """
    已采集商品过滤器
    用于全量商品明细重复采集时，过滤已采过的商品，避免重复采集
    """

    def __init__(self, batchNo=None):
        self.item_list = Mongo().get_collection('data_{}'.format(batchNo)).distinct("spuId")

    def contains(self, id):
        return id in self.item_list

    def put(self, id):
        self.item_list.append(id)


class SpuPageLogFilter(object):
    """
    已采集商品过滤器
    用于全量商品明细重复采集时，过滤已采过的商品，避免重复采集
    """

    def __init__(self, batchNo=None):
        self.item_list = Mongo().get_collection('spu_page_log_{}'.format(batchNo)).distinct("_id")

    def contains(self, cat_id, page):
        _id = 'c{}_p{}'.format(cat_id, page)
        return _id in self.item_list

    def put(self, id):
        self.item_list.append(id)


class ItemPageLogFilter(object):
    """
    已采集商品过滤器
    用于全量商品明细重复采集时，过滤已采过的商品，避免重复采集
    """
    def __init__(self, batchNo=None, coll_name=None, query={}, fields={'_id': 1}, filter_key='_id'):
        self.item_list = set()
        if not batchNo and not coll_name:
            raise BaseException('批次编号和集合名称至少指定一个')
        if not coll_name:
            coll_name = 'item_log_{}'.format(batchNo)
        items = Mongo().list(coll_name, query=query, fields=fields)
        for it in items:
            self.item_list.add(it.get(filter_key))

    def contains(self, id):
        return id in self.item_list

    def put(self, id):
        self.item_list.add(id)


class MaterialHelper(object):
    """
    物料编码补全工具
    """

    def __init__(self):
        self.material_map = dict()
        rows = Mongo().list('spu_pool', query={'materialCode': {'$exists': True}}, fields={'_id': 1, 'materialCode': 1})
        for row in rows:
            spu_id = row.get('_id')
            mt_code = row.get('materialCode')
            self.material_map[spu_id] = mt_code

    def fill(self, spu_list):
        todo_list = list()
        ok_list = list()
        if spu_list:
            for spu in spu_list:
                spu_id = spu.get('spuId')
                material_code = self.material_map.get(spu_id, '')
                if material_code:
                    spu['materialCode'] = material_code
                    ok_list.append(spu)
                else:
                    todo_list.append(spu)

        return ok_list, todo_list

if __name__ == '__main__':
    MaterialHelper().fill(list())